package com.ly.hotel.view.setting;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ly.hotel.R;
import com.ly.hotel.adaptor.NetworkUtil;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.SharedPreferencesConfig;

/**
 * 设置捷信达服务器ip
 * @author Administrator
 *
 */
public class SpaServerSettingLayout extends LinearLayout {

	private EditText serverIpText;
	private Button okBtn;
	private Button testBtn;
	private Context context;
	private TextView info;
	private Handler handler = new Handler();
	private boolean testting = false;
	private String hostIp;

	public SpaServerSettingLayout(Context context) {
		super(context);
		this.context = context;
		LayoutInflater.from(getContext()).inflate(R.layout.layout_syssetting, this);
		initView();
	}

	/*private void testServer(){
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(true){
					try {
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					String rv = NetworkUtil.pingHost();
					String lineTxt = "";
					
					BufferedReader bufferedReader = new BufferedReader(new StringReader(rv));
					String serverIp = "";
					String lost = "";
					
					try {
						while((lineTxt = bufferedReader.readLine()) != null){
							if(lineTxt.contains("packet loss")){
								String t[] = lineTxt.split(", ");
								if(t.length == 4){
									String tt[] = t[2].split(" ");
									if(tt.length == 3){
										lost = tt[0];
									}
									
								}
							}
							if(lineTxt.startsWith("PING")){
								String t[] = lineTxt.split(" ");
								serverIp = t[1];
							}
							
						    if(lineTxt.startsWith("rtt")){
//						    	Log.i("ping", lineTxt);
						    	String t[] = lineTxt.split("=");
						    	if(t.length == 2){
						    		String tt[] = t[1].split("/");
						    		if(tt.length == 4){
						    			Log.i("ping", "服务器" + serverIp + "网络延时:" + tt[1] + "ms" + ",丢包率" + lost);
						    		}
						    	}
						    }
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
	}*/
	private void testServer(){
		
		new Thread(){  
            public void run(){    
                handler.post(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						String rv = NetworkUtil.pingHost(5, hostIp);
						info.append(rv);
						
						String lineTxt = "";
						
						BufferedReader bufferedReader = new BufferedReader(new StringReader(rv));
						String serverIp = "";
						String lost = "";
						
						try {
							while((lineTxt = bufferedReader.readLine()) != null){
								if(lineTxt.contains("packet loss")){
									String t[] = lineTxt.split(", ");
									if(t.length == 4){
										String tt[] = t[2].split(" ");
										if(tt.length == 3){
											lost = tt[0];
											lost.replace(" ", "");
										}
										
									}
								}
								if(lineTxt.startsWith("PING")){
									String t[] = lineTxt.split(" ");
									serverIp = t[1];
								}
								
							    if(lineTxt.startsWith("rtt")){
//							    	Log.i("ping", lineTxt);
							    	String t[] = lineTxt.split("=");
							    	if(t.length == 2){
							    		String tt[] = t[1].split("/");
							    		if(tt.length == 4){
							    			Log.i("ping", "服务器" + serverIp + "网络延时:" + tt[1] + "ms" + ",丢包率" + lost);
							    			info.append("\r\n");
							    			info.append("局域网内，不允许超过3ms，否则影响电影和电视流畅性 \r\n");
							    			info.append("网络平均延时=" + tt[1] + "ms \r\n");
							    			if(lost.startsWith("0")){
							    				info.append("没丢包，再接再厉\r\n");
							    			} else if(lost.startsWith("25")){
							    				info.append("丢包率25%，怕会影响正常使用了.\r\n");
							    			} else if(lost.startsWith("50")){
							    				info.append("丢包率50%，怕会影响正常使用了.\r\n");
							    			} else if(lost.startsWith("75")){
							    				info.append("卧槽，这网不能用了..\r\n");
							    			} else if(lost.startsWith("100")){
							    				info.append("服务器IP不通，根据检查IP或者有没有设置对吧..\r\n");
							    			}
							    		}
							    	}
							    }
							}
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						testting = false;
					}
				});   
                }                     
        }.start();    
	}

	private void initView() {
		this.serverIpText = (EditText) findViewById(R.id.serverIpTxt);
		okBtn = (Button) findViewById(R.id.okBtn);
		testBtn = (Button) findViewById(R.id.testBtn);
		info = (TextView) findViewById(R.id.testInfoTxt);
		serverIpText.setText(SharedPreferencesConfig.getSpaServer(context));
		serverIpText.requestFocus();
		okBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (serverIpText.getText() == null 
						|| serverIpText.getText().toString().trim().equals("")) {
					Toast.makeText(context, "请输入SPA服务器IP以及端口", Toast.LENGTH_SHORT).show();
					return;
				}
				SharedPreferencesConfig.setSpaServer(context, serverIpText.getText().toString());
				MyApplication.setHost(SharedPreferencesConfig.getSpaServer(context));
				//新设置的地址要同步更新的Application里面
				MyApplication.setHostResUrl(MyApplication.getHost());
				Toast.makeText(context, "设置成功", Toast.LENGTH_SHORT).show();
			}
		});
		
		testBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				hostIp = serverIpText.getText().toString();
				// TODO Auto-generated method stub
				if(!testting){
					testting = true;
					info.clearComposingText();
					info.setText("正在测试服务器连通性，请稍等5秒....");
					testServer();
				} else {
					info.clearComposingText();
					info.setText("正在拼命的测试中，急啥....");
				}
			}
		});
	}
}
